<template>
  <div class="content-box w-card" v-if="!isDetail">
    <div class="title-box">
      <span class="title">售卡订单</span>
      <!-- <el-button style="margin-left:auto;" type="warning" plain @click="importHandle(1)">非在网订单导入</el-button> -->
      <el-button style="margin-left:auto;" type="primary" plain @click="importHandle(2)">批量同步状态</el-button>
      <el-button @click="exportHandle(1)">导出</el-button>
    </div>
    <div class="search-box">
      <div v-for="item in mySearchItem" :key="item" :style="{'width':(item.domType == 'el-date-picker')&&'26%'}">
        <component :is="item.domType" v-model="searchForm[item.bindValueName]" :type="item.type"
          :placeholder="typeof item.placeholder == 'string' ? item.placeholder : item.placeholder[0]"
          :range-separator="item.rangeSeparator"
          :start-placeholder="typeof item.placeholder == 'string' ? item.placeholder : item.placeholder[0]"
          :end-placeholder="typeof item.placeholder == 'string' ? item.placeholder : item.placeholder[1]"
          @keydown.enter="searchHandle" @change="searchHandle" :clearable="item.clearable">
          <component :is="'el-option'" v-for="items in item.selectList" :key="items.value" :label="items.label"
            :value="items.value"></component>
        </component>
      </div>
      <el-popover placement="bottom" width="calc(100% - 240px)" :visible="visible">
        <template #reference>
          <el-button style="margin-left: 0;" @click="visible = !visible">高级搜索</el-button>
        </template>
        <div class="pop-search-box">
          <div v-for="item in unmySearchItem" :key="item" :style="{'width':(item.domType == 'el-date-picker')&&'30%'}">
            <span>{{ item.name }}</span>
            <component :is="item.domType" v-model="searchForm[item.bindValueName]" :type="item.type"
              :placeholder="typeof item.placeholder == 'string' ? item.placeholder : item.placeholder[0]"
              :range-separator="item.rangeSeparator"
              :start-placeholder="typeof item.placeholder == 'string' ? item.placeholder : item.placeholder[0]"
              :end-placeholder="typeof item.placeholder == 'string' ? item.placeholder : item.placeholder[1]"
              @keydown.enter="searchHandle" @change="searchHandle" :clearable="item.clearable">
              <component :is="'el-option'" v-for="items in item.selectList" :key="items.value" :label="items.label"
                :value="items.value"></component>
            </component>
          </div>
        </div>
        <div class="faend">
          <el-button type="primary" @click="searchHandle">查询</el-button>
          <el-button style="margin-left: 10px;" @click="resetHandle">重置</el-button>
          <el-button style="margin-left: 10px;" @click="visible = false">关闭</el-button>
        </div>
      </el-popover>
      <el-button style="margin-left: 0;" @click="toEditSearchItem">自定义</el-button>
    </div>
    <div class="table-box">
      <el-table :max-height="tableHeight" :header-cell-style="{background:'#d6dee5',color:'#000000',fontSize:'14px'}"
        :cell-style="{fontSize:'14px',color:'#7b7b7d'}" :data="tableData" stripe @selection-change="handleSelectionChange">
        <el-table-column type="index" width="55" label="序号" align="left" />
        <el-table-column type="selection" width="55" />
        <el-table-column prop="sysOrderId" label="订单ID" align="left" min-width="120">
          <template v-slot="scope">
            <el-link type="primary" @click="lookDetail(scope.row.sysOrderId)">{{ scope.row.sysOrderId || '' }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="left" min-width="160">
          <template v-slot="scope">
            {{ scope.row.createTime ? getDateTime(scope.row.createTime)[6] : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="goodsName" label="商品名称" align="left">
          <template v-slot="scope">
            {{ scope.row.goodsName || '' }}
          </template>
        </el-table-column>
        <el-table-column prop="shopName" label="代理商" align="left">
          <template v-slot="scope">
            {{ scope.row.shopName || '' }}
          </template>
        </el-table-column>
        <el-table-column prop="goodsPhone" label="生产号码" align="left">
          <template v-slot="scope">
            {{ scope.row.goodsPhone || '' }}
          </template>
        </el-table-column>
        <el-table-column prop="goodsinfo" label="收件信息" align="left" min-width="180">
          <template v-slot="scope">
            <div class="goodsinfo-box">
              <div class="unimp">证件姓名：{{ scope.row.idcardName || '' }}</div>
              <div class="unimp">证件号码：{{ scope.row.idcardNum || ''  }}</div>
              <div class="unimp">收件人：{{ scope.row.receiverName || ''  }}</div>
              <div class="unimp">联系电话：{{ scope.row.receivePhone || ''  }}</div>
              <div class="unimp">收件地址：{{ scope.row.receiveAddress || ''  }}</div>
              <div class="unimp">物流单号：{{ scope.row.logisticsNum || ''  }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="orderStatus" label="订单状态" align="left" min-width="140">
          <template v-slot="scope">
            <div class="goodsinfo-box">
              <div class="unimp">
                {{ scope.row.orderStatus == 5 ? '待支付' : scope.row.orderStatus == 10 ? '订单进行中' : scope.row.orderStatus == 20 ? '受理成功' : scope.row.orderStatus == 30 ? '订单异常结束' : scope.row.orderStatus == 40 ? '订单异常待处理' : '' }}
              </div>
              <div class="unimp">
                激活状态：{{ scope.row.activeStatus == 0 ? '未激活' : scope.row.activeStatus == 10 ? '已下单' : scope.row.activeStatus == 12 ? '激活中' : scope.row.activeStatus == 14 ? '下单失败' : scope.row.activeStatus == 20 ? '激活成功' : scope.row.activeStatus == 22 ? '激活成功且充值成功' : scope.row.activeStatus == 30 ? '激活失败' : ''  }}
              </div>
              <div class="unimp">首充结果：{{ scope.row.chargeResult || ''  }}</div>
            </div>

          </template>
        </el-table-column>
        <el-table-column prop="orderStatusMsg" label="备注" align="left">
          <template v-slot="scope">
            {{ scope.row.orderStatusMsg }}
          </template>
        </el-table-column>
        <el-table-column prop="Operations" label="操作" align="center" width="100" fixed="right">
          <template v-slot="scope">
            <div class="table-handle-box">
              <el-link style="font-size:14px" type="primary" @click="zhuangtaitb(scope.row.sysOrderId)">同步状态</el-link>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="my-table-footer">
        <div>
          <el-button :disabled="chooseList.length == 0" @click="exportHandle(2)">批量导出</el-button>
        </div>
        <el-pagination style="margin-left:auto;" v-model:currentPage="page" v-model:page-size="size"
          :page-sizes="[10, 20, 50, 100]" small :background="true" layout="total, sizes, prev, pager, next, jumper" :total="total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
  <edit-search-item ref="editSearchItemRef" @dialogClose="dialogClose" />
  <in-out-dialog ref="inOutDialogRef" @dialogClose="inOutdialogClose" />
  <router-view></router-view>
</template>

<script>
import { BlobDownLoad, getDateTime, getWindowWidthAndHeight, successDeal, warningDeal } from '@/utils/utils'
import { onMounted, reactive, ref, toRefs, watch } from 'vue'
import editSearchItem from './editSearchItem.vue'
import searchItem from './searchItem'
import api from '../api'
import { useRoute, useRouter } from 'vue-router'
import inOutDialog from './inOutDialog.vue'
export default {
  components: {
    editSearchItem,
    inOutDialog,
  },
  setup() {
    const route = useRoute()
    const router = useRouter()

    const editSearchItemRef = ref(null)
    const inOutDialogRef = ref(null)

    const state = reactive({
      isDetail: false,
      visible: false,
      searchForm: {},

      tableHeight: 0,
      page: 1,
      size: 10,
      total: 0,
      tableData: [],
      chooseList: [],

      mySearchItem: [],
      unmySearchItem: [],
    })

    watch(() => route.path, (newVal, oldVal) => {
      setIsDetail()
    })

    function setIsDetail() {
      state.isDetail = (route.path != '/orderMng/sellCardsOrder')
    }


    function getTableData() {
      const obj = {
        orderBy: 'id desc',
        page: state.page,
        size: state.size,
        ...state.searchForm,
        createTimeMin: (state.searchForm.date && state.searchForm.date[0]) ? (state.searchForm.date[0]).getTime() : null,
        createTimeMax: (state.searchForm.date && state.searchForm.date[1]) ? (state.searchForm.date[1]).getTime() : null,
      }
      api.orderQryList(obj).then(res => {
        if (res.code == '200') {
          state.tableData = res.data.list
          state.total = res.data.total
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function handleCurrentChange(e) {
      state.page = e
      getTableData()
    }

    function handleSizeChange(e) {
      state.size = e
      getTableData()
    }

    function searchHandle() {
      state.page = 1
      getTableData()
    }

    function resetHandle() {
      state.page = 1
      state.searchForm = {}
      getTableData()
    }

    function handleSelectionChange(e) {
      state.chooseList = e
    }

    function getSearchItem() {
      const myList = JSON.parse(window.localStorage.getItem('SEARCHITEM_INRE'))
      if (!myList || myList.length == 0) {
        const uList = []
        searchItem.map(item => {
          if (!item.isCommonlysed) return
          uList.push(item)
        })
        window.localStorage.setItem('SEARCHITEM_INRE', JSON.stringify(uList))
        state.mySearchItem = uList
      } else {
        state.mySearchItem = myList
      }
      state.unmySearchItem = searchItem.filter(item => !state.mySearchItem.some(ele => ele.id === item.id))
    }

    function toEditSearchItem() {
      editSearchItemRef.value.dialogShow()
    }

    function dialogClose() {
      getSearchItem()
    }

    function inOutdialogClose() {
      getTableData()
    }

    function exportHandle(type) {
      let obj = {}
      switch (type) {
        case 1:
          obj = {
            page: state.page,
            size: state.size,
            ...state.searchForm,
            createTimeMin: (state.searchForm.date && state.searchForm.date[0]) ? (state.searchForm.date[0]).getTime() : null,
            createTimeMax: (state.searchForm.date && state.searchForm.date[1]) ? (state.searchForm.date[1]).getTime() : null,
          }
          break
        case 2:
          obj = {
            page: state.page,
            size: state.size,
            sysOrderId: getSysOrderId(state.chooseList).join(','),
          }
          break
      }
      api.orderQryListDown({ ...obj, responseType: "blob" }).then(res => {
        const _fileName = decodeURIComponent(res.headers['content-disposition'].split(';')[1].split('=')[1])
        BlobDownLoad(res, _fileName)
      }).catch(err => {
        console.log(err)
      })
    }

    function getSysOrderId(list) {
      const myArr = []
      list && list.map(item => {
        myArr.push(item.sysOrderId)
      })
      return myArr
    }

    function importHandle(type) {
      inOutDialogRef.value.dialogShow(type)
    }

    function zhuangtaitb(sysOrderId) {
      const obj = {
        sysOrderId
      }
      api.statusRefresh(obj).then(res => {
        if (res.code == '200') {
          successDeal(res.msg)
          getTableData()
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function lookDetail(sysOrderId) {
      router.push({ path: '/orderMng/sellCardsOrder/orderDetail', query: { sysOrderId } })
    }

    onMounted(() => {
      setIsDetail()
      let winHeight = getWindowWidthAndHeight()
      state.tableHeight = winHeight.windowHeight - 300
      getSearchItem()
      getTableData()
    })

    return {
      ...toRefs(state),
      editSearchItemRef,
      inOutDialogRef,
      getDateTime,
      handleCurrentChange,
      handleSizeChange,
      searchHandle,
      resetHandle,
      toEditSearchItem,
      dialogClose,
      exportHandle,
      handleSelectionChange,
      importHandle,
      inOutdialogClose,
      zhuangtaitb,
      lookDetail,
    }
  }
}
</script>

<style lang="scss" scoped>
.content-box {
  height: 100%;
  box-sizing: border-box;
  padding: 20px;
  overflow: hidden;
  overflow-y: auto;
  .title-box {
    display: flex;
    align-items: center;
    > .title {
      font-size: 16px;
      font-weight: bold;
    }
  }
  .search-box {
    margin-top: 20px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
    > div {
      width: 16%;
      display: flex;
      align-items: center;
      gap: 10px;
      > span {
        flex-shrink: 0;
        font-size: 14px;
      }
    }
  }
  .table-box {
    margin-top: 20px;
    .my-table-footer {
      display: flex;
      align-items: center;
      margin-top: 10px;
    }
    .table-handle-box {
      display: flex;
      justify-content: space-around;
    }
  }
}
.pop-search-box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 20px;
  > div {
    width: 20%;
    display: flex;
    align-items: center;
    gap: 10px;
    > span {
      flex-shrink: 0;
      font-size: 14px;
    }
  }
}
.faend {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
.unimp {
  font-size: 12px;
}
</style>